package cn.edu.zzuli.wechat.user.service.impl;

import cn.edu.zzuli.common.constant.RabbitConstant;
import cn.edu.zzuli.common.exception.CustomException;
import cn.edu.zzuli.model.dto.OfferOrderDto;
import cn.edu.zzuli.model.dto.RankDto;
import cn.edu.zzuli.model.entity.OfferOrder;
import cn.edu.zzuli.model.entity.User;
import cn.edu.zzuli.model.vo.order.AllOfferOrderQueryVo;
import cn.edu.zzuli.model.vo.order.ConditionQueryVo;
import cn.edu.zzuli.model.vo.all.SelectQuery;
import cn.edu.zzuli.wechat.login.mapper.ListMapper;
import cn.edu.zzuli.wechat.user.mapper.OfferOrderMapper;
import cn.edu.zzuli.wechat.user.mapper.UserMapper;
import cn.edu.zzuli.wechat.user.service.OfferOrderService;
import cn.edu.zzuli.common.utils.NowDate;
import cn.edu.zzuli.common.utils.SensitiveFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OfferOrderServiceImpl extends ServiceImpl<OfferOrderMapper, OfferOrder> implements OfferOrderService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ListMapper listMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发布订单
     * @param order
     * @param session
     * @return
     */
    @Override
    public int addOfferOrder(OfferOrder order, HttpSession session) {
        //建立过滤对象
        SensitiveFilter sensitiveFilter = new SensitiveFilter();
        //对发布订单改变
        Integer uid = (Integer) session.getAttribute("uid");
        order.setOuid(uid);
        order.setPostTime(NowDate.getNowTimes());
        //敏感词过滤
        String describedFilter = sensitiveFilter.filter(order.getDescribed());
        order.setDescribed(describedFilter);
        String titleFilter = sensitiveFilter.filter(order.getTitle());
        order.setTitle(titleFilter);
        //检查余额是否充足
        double wealth = userMapper.getUserWealth(uid);
        if(wealth < order.getBounty()){
            throw new CustomException("余额不足!请充值!");
        }

        //存入数据库
        int res = baseMapper.insert(order);
        if (res == 0){
            throw new CustomException("发布错误,请再试一次!");
        }


        if(order.getBounty() >= 16){
            rabbitTemplate.convertAndSend(RabbitConstant.EXCHANGE,RabbitConstant.ROUTING_KEY_BROADCAST_MESSAGES
                    ,"有用户发布了高达" + order.getBounty() + "元的订单,手慢则无啊|" + uid);
        }

        //扣除积分
        this.updateUserWealth(uid, wealth - order.getBounty());

        return res;
    }

    /**
     * 条件分页查询所有用户订单
     * @param queryVo
     * @return
     */
    @Override
    public Map<String, Object> queryOfferList(AllOfferOrderQueryVo queryVo) {
        //分页查询
        Page<OfferOrderDto> pageCod = new Page<>(queryVo.getPage(),queryVo.getLimit());
        //条件查询
        QueryWrapper<OfferOrderDto> wrapper = new QueryWrapper<>();
        if(queryVo.getType() != null){
            wrapper.eq("type", queryVo.getType());
        }
        wrapper.gt("dead_time", NowDate.getNowTimes()).eq("status",0)
                .orderByDesc("bounty");
        Page<OfferOrderDto> offerOrderPage = baseMapper.queryList(pageCod, wrapper);

        //获得map集合
        Map<String,Object> map = this.getResultMap(offerOrderPage);
        return map;
    }

    /**
     * 所有用户的订单列表
     * @param queryVo
     * @return
     */
    @Override
    public Map<String, Object> queryOfferOrderList(AllOfferOrderQueryVo queryVo) {
        return this.queryOfferList(queryVo);
    }


    /**
     * 排行榜
     * @param selectQuery
     * @return
     */
    @Override
    public Map<String, Object> queryByOrderCount(SelectQuery selectQuery) {
        Page<RankDto> page = new Page<>(selectQuery.getPage(),selectQuery.getLimit());
        Page<RankDto> rankDtoList = baseMapper.selectRankList(page);
        Map<String, Object> resultMap = this.getResultMap(rankDtoList);
        return resultMap;
    }

    /**
     *
     * @param selectQuery
     * @param status
     * @param uid
     * @return
     */
    @Override
    public Map<String, Object> queryOfferOwnOrder(SelectQuery selectQuery, Integer status, Integer uid) {
        //分页查询
        Page<OfferOrderDto> page = new Page<>(selectQuery.getPage(),selectQuery.getLimit());
        //条件查询
        QueryWrapper<OfferOrderDto> wrapper = new QueryWrapper<>();
        if(status != null){
            wrapper.eq("status", status);
        }
        wrapper.eq("ouid",uid);
        Page<OfferOrderDto> orderDtoPage = baseMapper.queryListByStatus(page,wrapper);
        return this.getResultMap(orderDtoPage);
    }

    @Override
    public Map<String, Object> choose(ConditionQueryVo conditionQueryVo, SelectQuery selectQuery) {
        //分页查询
        Page<OfferOrder> page = new Page<>(selectQuery.getPage(),selectQuery.getLimit());
        Page<OfferOrder> orderDtoPage = baseMapper.choose(conditionQueryVo,page);
        return this.getResultMap(orderDtoPage);
    }

    @Override
    public void sureFinish(Integer id, String finishTime,Integer uid) {
        String deadTime = baseMapper.getDeadTime(id);
        Integer res = null;
        System.out.println(finishTime);
        System.out.println(deadTime);
        if(NowDate.stringToDate(finishTime).getTime() <= NowDate.stringToDate(deadTime).getTime()){
            res = baseMapper.updateById(new OfferOrder(id,2));
        }else{
            res = baseMapper.updateById(new OfferOrder(id,6));
        }
        userMapper.updateCredit(uid);
    }

    @Override
    public void edit(OfferOrder order) {
        if(order.getSendPlace() == ""){
            order.setSendPlace(null);
        }
        if(order.getPickPlace() == ""){
            order.setPickPlace(null);
        }
        if(order.getDescribed() == ""){
            order.setDescribed(null);
        }
        if(order.getTitle() == ""){
            order.setTitle(null);
        }
        if(order.getDeadTime() == ""){
            order.setDeadTime(null);
        }
        baseMapper.updateById(order);
    }


    //获取map集合抽取的方法
    private Map<String, Object> getResultMap(Page offerOrderPage) {
        List<Object> lists  = offerOrderPage.getRecords();
        long  total = offerOrderPage.getTotal();
        Map<String, Object> map;
        map = new HashMap<>();
        map.put("code",200);
        map.put("msg","success");
        map.put("count",total);
        map.put("data",lists);
        return map;
    }


    //更新订单状态抽取的方法
    private void updateUserWealth(Integer uid,Double bounty){
        User user = new User();
        user.setUid(uid);
        user.setWealth(bounty);
        userMapper.updateById(user);
    }
}
